var db = require('../model/db')
var middleware = require('./middlewareCtrl')
var formidable = require('formidable')
var path = require('path')

// 新增说明
module.exports.AddExplain = (req, res) => {
  const keys = Object.keys(req.body);
  const values = Object.values(req.body);
  const placeholders = values.map(() => '?').join(', ');
  const sql = `INSERT INTO product_Explain (${keys.join(', ')}) VALUES (${placeholders})`;
  db.dbSql(sql, values, (err, results) => {
    if (err) { console.error(err); return res.status(500).json({ code: 500, msg: '新增失败！' }); }
    res.json({ code: 200, msg: '新增成功！', data: results });
  });

}
// 查看说明
module.exports.showExplain = (req, res) => {
  middleware.getAllRecords('product_explain', res)
}

// 删除说明
module.exports.deletsExplain = (req, res) => {
  var data = req.body.id
  console.log(data);
  middleware.deleteRecord('product_explain', res, data, 'id')
}
// 新增类别
module.exports.AddType = (req, res) => {
  const { type_id, type_name, type_describe } = req.body;
  const sql = 'INSERT INTO product_type VALUES (?, ?, ?)';
  const data = [type_id, type_name, type_describe]
  db.dbSql(sql, data, (err, results) => {
    if (err) {
      return res.send({ code: 101, msg: '新增失败！' });
    } else {
      res.send({ code: 200, msg: '新增成功！' });
    }
  })
}
// 查看类别
module.exports.showType = (req, res) => {
  middleware.getAllRecords('product_type', res)
}
// 删除类别
module.exports.deletsType = (req, res) => {
  var data = req.body.type_id
  middleware.deleteRecord('product_type', res, data, 'type_id')
}
// 新增规格
module.exports.AddSpecs = (req, res) => {
  middleware.dbInsert('specs', req.body, res)
}
// 查看规格
module.exports.showSpecs = (req, res) => {
  middleware.getAllRecords('specs', res)
}
// 查看商品规格分页
module.exports.showPageSpecs = (req, res) => {
  middleware.page('specs', req, res, 'specs_id')
}
// 删除规格
module.exports.deletsSpecs = (req, res) => {
  var data = req.body.specs_id
  middleware.deleteRecord('specs', res, data, 'specs_id')
}
// 查看商品
module.exports.showProduct = (req, res) => {
  middleware.getAllRecords('product', res)
}

// 查看商品和规格
module.exports.showProductSpecs = (req, res) => {
  var sql = ` SELECT * from product,specs where specs.specs_id=product.specs_id  `
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}
// 分页展示商品
module.exports.showPageProduct = (req, res) => {
  middleware.page('product', req, res, 'product_id')
}
// 查看商品所有信息,规格（前台）
module.exports.showProductAll = (req, res) => {
  var id = req.query.product_id
  console.log(id);
  var sql = ` SELECT * from product,specs where specs.specs_id=product.specs_id and product.product_id=?;
  SELECT * from product,product_explain where product_explain.explain_id=product.explain_id and product.product_id=?`
  db.dbSql(sql, [id, id], (err, results) => {
    console.log(sql);
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！', err: err });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });

  })
}
// 新增商品
module.exports.AddProduct = (req, res) => {
  middleware.dbInsert('product', req.body, res)
}
// 删除商品
module.exports.deletsProduct = (req, res) => {
  var data = req.body.product_id
  middleware.deleteRecord('product', res, data, 'product_id')
}
// 修改商品
module.exports.updateProduct = (req, res) => {
  var data = req.body
  middleware.updateById('product', data, 'product_id', res)
}
// 查看轮播图
module.exports.showBanner = (req, res) => {
  middleware.getAllRecords('banner', res)
}
// 新增轮播图
module.exports.AddBanner = (req, res) => {
  middleware.dbInsert('banner', req.body, res)

}
// 删除轮播图
module.exports.deletsBanner = (req, res) => {
  var data = req.body.banner_id
  console.log(data);
  middleware.deleteRecord('banner', res, data, 'banner_id')
}
// 更新轮播图
module.exports.updataBanner = (req, res) => {
  const data = req.body
  middleware.updateById('banner', data, 'banner_id', res)
}
// 分页展示轮播图
module.exports.showPageBanner = (req, res) => {
  middleware.page('banner', req, res, 'banner_id')
}


// 展示购物车页面
module.exports.showShopcart = (req, res) => {
  var sql = `SELECT * FROM shopcart,goods,user WHERE shopcart.g_id=goods.g_id AND shopcart.u_id=user.u_id AND user.u_id=?;`;
  var u_id = req.data.user_id;
  db.dbSql(sql, [u_id], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}

// 加入购物车
module.exports.addShoppingCart = (req, res) => {
  var shopcart = req.body
  const sql = ` SELECT * FROM shopping_cart WHERE user_id=${req.user.user_id} and product_id=${shopcart.product_id}`;
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '新增失败！' });
    if (results.length == 0) {
      //新增一条
      console.log(shopcart.product_specs);
      var sql2 = `INSERT INTO shopping_cart (user_id,product_id,pay_amount,product_specs) VALUES (${req.user.user_id},${shopcart.product_id},${shopcart.pay_amount},'${JSON.stringify(shopcart.product_specs)}')`;
      db.dbSql(sql2, [], (err, results) => {
        if (err) return res.status(500).json({ code: 500, msg: '新增失败！' });
        res.status(200).json({ code: 200, msg: '新增成功！', data: results });
      })
    } else {
      //说明该用户购物车已经有这条商品，只增加数量
      var sql3 = `UPDATE shopping_cart SET pay_amount=pay_amount+${shopcart.pay_amount} WHERE product_id=${shopcart.product_id} AND  user_id=${req.user.user_id};`;
      db.dbSql(sql3, [], (err, results) => {
        if (err) return res.status(500).json({ code: 500, msg: '新增失败！' });
        res.status(200).json({ code: 200, msg: '新增成功！', data: results });
      })
    }
  })
}
//展示购物车页面
module.exports.showShopcart = function (req, res) {
  var u_id = req.user.user_id;
  var sql = `SELECT * FROM shopping_cart,product,user WHERE shopping_cart.product_id=product.product_id
  AND shopping_cart.user_id=user.user_id AND user.user_id=${u_id};`;
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}

// 将商从购物车中删除
module.exports.delShopCart = function (req, res) {
  var cart_id = req.body.cart_id;
  var sql = `delete from shopping_cart where cart_id=${cart_id}`;
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '删除失败！' });
    res.status(200).json({ code: 200, msg: '删除成功！', data: results });
  })
}
// 修改商品数量
module.exports.updateCart = function (req, res) {
  var cart_id = req.body.cart_id;
  var num = req.body.num;
  var sql = `UPDATE shopping_cart set pay_amount=${num} where cart_id=${cart_id};`
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '修改失败！' });
    res.status(200).json({ code: 200, msg: '修改成功！', data: results });
  })
}
// 清空购物车
module.exports.clearCart = function (req, res) {
  var cart_ids = req.body;
  var sql = `DELETE FROM shopping_cart WHERE cart_id IN (?);`
  db.dbSql(sql, cart_ids, (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '修改失败！' });
    res.status(200).json({ code: 200, msg: '修改成功！', data: results });
  })
}


// 查看商品评价
module.exports.showProductReview = (req, res) => {
  var id = req.query.product_id
  const sql = `SELECT * from product_review ,user where product_review.user_id=user.user_id and  product_id=?`
  db.dbSql(sql, [id], (err, results) => {
    console.log(sql);
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}

// 新增商品评价
module.exports.AddProductReview = (req, res) => {
  req.body.user_id = req.user.user_id
  console.log(req.body);
  middleware.dbInsert('product_review', req.body, res)
}

// // 查看商品说明
// module.exports.showProductExplain=(req,res)=>{
//   var id=req.query.product_id
//   const sql=`  SELECT * from product_explain where product_id=?`
//   db.dbSql(sql, [id], (err, results) => {
//     if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
//     res.status(200).json({ code: 200, msg: '查询成功！', data: results });
//   })
// }


// 添加订单
module.exports.AddOrder = (req, res) => {
  let sql = ''
  if (Array.isArray(req.body)) {
    // 如果是数组，不做处理
  } else {
    // 如果不是数组，将其转换为数组
    req.body = [req.body];
  }
  req.body.forEach(item => {
    item.user_id = req.user.user_id
    item.product_specs = JSON.stringify(item.product_specs)
    let keys = Object.keys(item);
    let values = Object.values(item);
    let placeholders = values.map((item) => `'${item}'`).join(',');
    sql += `INSERT INTO orders (${keys.join(', ')}) VALUES (${placeholders});`;
  })
  console.log(sql);
  db.dbSql(sql, [], (err, results) => {
    if (err) { console.error(err); return res.status(500).json({ code: 500, msg: '新增失败！' }); }
    res.json({ code: 200, msg: '新增成功！', data: results });
  });
}

// 查询订单
module.exports.showOrders = (req, res) => {
  var u_id = req.user.user_id;
  var sql = `SELECT * FROM orders 
             INNER JOIN product ON orders.product_no = product.product_no 
             INNER JOIN user ON orders.user_id = user.user_id 
             WHERE user.user_id=${u_id};`;
  db.dbSql(sql, [], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    console.log(results);
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}

// 分页展示个人订单
module.exports.showPageOrderGe = (req, res) => {
  var u_id = req.user.user_id;
  var { pageNum, pageSize } = req.query
  // 参数验证
  if (!pageNum || !pageSize || pageNum <= 0 || pageSize <= 0) {
    return res.status(400).json({ code: 400, msg: '参数错误' })
  }
  var offset = (--pageNum) * pageSize
  var sql = `SELECT * FROM orders 
  INNER JOIN product ON orders.product_no = product.product_no 
  INNER JOIN user ON orders.user_id = user.user_id 
  WHERE user.user_id=${u_id} LIMIT ?, ?`
  console.log(sql);
  db.dbSql(sql, [offset, parseInt(pageSize)], function (err, results) {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败' })
    res.json({ code: 200, msg: '查询成功!', data: results })
  })
}

// 查看所有订单
module.exports.OrdersAll = (req, res) => {
  middleware.getAllRecords('orders', res)
}
// 分页展示订单
module.exports.showPageOrders = (req, res) => {
  middleware.page('orders', req, res, 'order_id')
}
// 查看退货原因
module.exports.showReturn = (req, res) => {
  middleware.getAllRecords('return_reason', res)
}
// 修改退货原因
module.exports.updataReturn = (req, res) => {
  const data = req.body
  middleware.updateById('return_reason', data, 'reason_id', res)
}


// 查看收藏
module.exports.showProductCollect = (req, res) => {
  var id = req.query.product_id
  const sql = `SELECT * from collect where product_id=?;SELECT * from collect,user where user.user_id=collect.user_id  and product_id=?`
  db.dbSql(sql, [id, id], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}
// 查看个人收藏
module.exports.showCollect = (req, res) => {
  var id = req.user.user_id
  const sql = ` SELECT * from collect , product where collect.product_id=product.product_id and user_id=?`
  db.dbSql(sql, [id], (err, results) => {
    if (err) return res.status(500).json({ code: 500, msg: '查询失败！' });
    res.status(200).json({ code: 200, msg: '查询成功！', data: results });
  })
}
// 增加商品收藏
module.exports.AddCollect = (req, res) => {
  req.body.user_id = req.user.user_id
  console.log(req.body);
  middleware.dbInsert('collect', req.body, res)
}
// 删除商品收藏
module.exports.deletsCollect = (req, res) => {
  var data = req.query.collect_id
  console.log(data);
  middleware.deleteRecord('collect', res, data, 'collect_id')
}

// 上传图片
module.exports.upload = (req, res) => {
  var form = 
  ({
    multiples: true,
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../public/upload')
  });  
  form.parse(req, (err, fields, files) => {
    if (err) {
      throw err;
    }
    res.json({
      code: 200,
      err: null,
      url: "http://localhost:3000/public/upload/" + files.file.newFilename // 复制URL链接直接浏览器可以访问
    });
  })
}
// 上传商品图片
module.exports.productImg = (req, res) => {
  var form = formidable({  
    multiples: true,
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../public/product')
  });
  form.parse(req, (err, fields, files) => {
    if (err) {
      throw err;
    }
    res.json({
      code: 200,
      err: null,
      url: "http://localhost:3000/public/product/" + files.file.newFilename // 复制URL链接直接浏览器可以访问
    });
  })
}

module.exports.search = (req, res) => {
  var content = req.query
  middleware.search('user', 'user_name', res, content)
}